package com.dong.aoptools.premain.handler;

import com.dong.aoptools.cast.cls.ClassAOPVisitor;
import com.dong.aoptools.constant.PropertiesConst;
import com.dong.aoptools.util.PathUtils;
import com.dong.aoptools.util.PropertiesUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @description: 输出内存中的类文件的处理器
 * @author: 陈瑞东
 * @create: 2021-11-29 15:38
 */
public class OutputLoadedClassHandler implements CommonHandler {

    @Override
    public byte[] doHandler(ClassLoader loader, String className, byte[] classfileBuffer) {
        // 获取配置的包含类名
        String containClass = PropertiesUtils.getConfigProperty(PropertiesConst.CONFIG_FIELD_OUTPUT_PRINT_CLASS, "com.dong");
        // 将 . 转成 /
        containClass = PathUtils.point2Slash(containClass);
        // 过滤类
        if (className.contains(containClass)) {
            return getBytes(loader, className, classfileBuffer);
        }
        return classfileBuffer;
    }

    private byte[] getBytes(ClassLoader loader, String className, byte[] classfileBuffer) {
        Properties p = new Properties();
        String path = PropertiesUtils.getConfigProperty(PropertiesConst.CONFIG_FIELD_OUTPUT_PATH, "");
        // 判断配置是否为空
        if (path == null || "".equals(path.trim())) {
            return classfileBuffer;
        }
        File file = new File(path, className + ".class");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }


        try (
            FileOutputStream fileOutputStream = new FileOutputStream(file)
        ) {
            fileOutputStream.write(classfileBuffer);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return classfileBuffer;
    }
}
